package tool

import (
	"crypto/sha256"
	"encoding/hex"
)

// 计算 Merkle 根
func MerkleRoot(data [][]byte) string {
	if len(data) == 0 {
		return "" // 处理空输入情况
	}
	if len(data) == 1 {
		hash := sha256.Sum256(data[0])
		return hex.EncodeToString(hash[:]) // 转换为切片后编码
	}

	var newLevel [][]byte
	for i := 0; i < len(data); i += 2 {
		if i+1 == len(data) {
			// 处理奇数情况，复制最后一个元素
			data = append(data, data[i])
		}
		h := sha256.Sum256(append(data[i], data[i+1]...))
		newLevel = append(newLevel, h[:])
	}
	return MerkleRoot(newLevel)
}
